package edu.javeriana.aes.psw.receiver;

import edu.javeriana.aes.psw.context.ControllerListener;
import edu.javeriana.aes.psw.mensaje.Mensaje;
import edu.javeriana.aes.psw.mensaje.MensajeBean;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPReceiver implements Receiver {

    private boolean isAlive = true;
    private ServerSocket serverSocket;
    private ControllerListener controllerListener;

    public TCPReceiver(ControllerListener controllerListener) throws IOException {
        serverSocket = new ServerSocket(8899);
        this.controllerListener = controllerListener;
    }

    @Override
    public void recibir() {
        while (isAlive) {
            try {
                Socket cliente = serverSocket.accept();
                Thread thread = new Thread(new ClienteSocket(cliente));
                thread.start();
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    }

    @Override
    public void finalizar() {
        isAlive = false;
        try {
            serverSocket.close();
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }

    private class ClienteSocket implements Runnable {

        private Socket cliente;

        public ClienteSocket(Socket cliente) {
            this.cliente = cliente;
        }

        @Override
        public void run() {
            try {
                DataInputStream dis = new DataInputStream(cliente.getInputStream());

                double temperatura = dis.readDouble();
                long timestamp = dis.readLong();
                int frecuencia = dis.readInt();

                byte[] ip = new byte[15];
                dis.read(ip);

                byte[] hostname = new byte[20];
                dis.read(hostname);

                Mensaje mensaje = new MensajeBean(
                        new String(ip),
                        new String(hostname),
                        temperatura,
                        timestamp,
                        frecuencia);

                controllerListener.notificarMensajeTCP(mensaje);
                cliente.close();
                dis.close();
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    }
}
